package com.wholesale.utils;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.wholesale.R;
import com.wholesale.beans.GoodsInfo;
import com.wholesale.datas.WebServiceClient;
import com.wholesale.utils.AsyncImageLoader.ImageCallback;

public class GoodsListAdapter extends ArrayAdapter<GoodsInfo> {

	public final static int ACTION_UNDERLIST = 1;
	public final static int ACTION_GOODSLIST = 2;
	public final static int ACTION_NEWGOODSLIST = 3;
	public final static int ACTION_HOTGOODSLIST = 4;
	public final static int ACTION_SEARCHGOODSLIST = 5;
	public final static int ACTION_GOODSLISTBYCARTID = 6;
	List<GoodsInfo> goodsInfoList = new ArrayList<GoodsInfo>();
	private ListView listView;
	private AsyncImageLoader loader;
	private boolean isAsyncLoadData;
	private LinearLayout loadingLayout;
	private Thread thread;
	private GoodsListListAsync task;
	private int lastItem;
	// 总页数
	private int pageNum;
	// 排序字段
	private String shortBy;
	// 是否升序
	private boolean desc;
	// 动作类型
	private int action;
	// 当前页数
	private int curPage = 1;
	// 分类ID
	private int catId;

	// 查询条件
	private String condition;

	public GoodsListAdapter(Context context, ListView listView) {
		super(context, 0);
		this.listView = listView;
		loader = AsyncImageLoader.getInstance();
	}

	public GoodsListAdapter(Context context, List<GoodsInfo> GoodsInfoList,
			ListView listView) {
		super(context, 0, GoodsInfoList);
		this.listView = listView;
		loader = AsyncImageLoader.getInstance();
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		Activity activity = (Activity) getContext();

		// Inflate the views from XML
		View rowView = convertView;
		GoodsCache viewCache;
		if (rowView == null) {
			LayoutInflater inflater = activity.getLayoutInflater();
			rowView = inflater.inflate(R.layout.goodsitems, null);
			viewCache = new GoodsCache(rowView);
			rowView.setTag(viewCache);
		} else {
			viewCache = (GoodsCache) rowView.getTag();
		}
		GoodsInfo goodsInfo = getItem(position);

		// Load the image and set it on the ImageView
		String imageUrl = goodsInfo.getGoodsThumb();
		ImageView imageView = viewCache.getGoodsImage();
		imageView.setTag(imageUrl);
		Drawable cachedImage = loader.loadDrawable(imageUrl,
				new ImageCallback() {
					public void imageLoaded(Drawable imageDrawable,
							String imageUrl) {
						ImageView imageViewByTag = (ImageView) listView
								.findViewWithTag(imageUrl);
						if (imageViewByTag != null) {
							imageViewByTag.setImageDrawable(imageDrawable);
						}
					}
				});
		if (cachedImage == null) {
			imageView.setImageResource(R.drawable.loading);
		} else {
			imageView.setImageDrawable(cachedImage);
		}
		// Set the text on the TextView
		viewCache.getGoodsName().setText(goodsInfo.getGoodsName());
		viewCache.getGoodsPrice().setText("US$ " + goodsInfo.getShopPrice());
		viewCache.getGoodsPrice().setTextColor(Color.RED);

		// Comment by dave 设置new和promote
		// if (goodsInfo.isNew()) {
		// viewCache.getNewImage().setVisibility(View.VISIBLE);
		// } else {
		// viewCache.getNewImage().setVisibility(View.INVISIBLE);
		// }
		// if (goodsInfo.isPromote()) {
		// viewCache.getPromoteImage().setVisibility(View.VISIBLE);
		// } else {
		// viewCache.getPromoteImage().setVisibility(View.INVISIBLE);
		// }
		return rowView;
	}

	public void setPageNum(int action, int number, String shortBy, boolean desc) {
		this.action = action;
		this.pageNum = number;
		this.shortBy = shortBy;
		this.desc = desc;
		curPage = 1;
	}

	public void setPageNum(int action, int catId, int number, String shortBy,
			boolean desc) {
		this.action = action;
		this.catId = catId;
		this.pageNum = number;
		this.shortBy = shortBy;
		this.desc = desc;
		curPage = 1;
	}

	public void setPageNum(int action, String condition, int number,
			String shortBy, boolean desc) {
		this.action = action;
		this.condition = condition;
		this.pageNum = number;
		this.shortBy = shortBy;
		this.desc = desc;
		curPage = 1;
	}

	public void setAsyncLoadData(boolean asyncLoadData) {
		this.isAsyncLoadData = asyncLoadData;
		getLoadView();
		loadingLayout.setVisibility(View.GONE);
		listView.addFooterView(loadingLayout, null, false);
		listView.setFooterDividersEnabled(false);
		this.listView.setOnScrollListener(scrollListener);
	}

	private void getLoadView() {
		if (loadingLayout == null) {
			LinearLayout searchLayout = new LinearLayout(getContext());
			searchLayout.setOrientation(LinearLayout.HORIZONTAL);
			ProgressBar progressBar = new ProgressBar(getContext());
			progressBar.setPadding(0, 0, 15, 0);
			searchLayout.addView(progressBar, new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.FILL_PARENT,
					LinearLayout.LayoutParams.FILL_PARENT));
			searchLayout.setGravity(Gravity.CENTER);

			TextView loadView = new TextView(getContext());
			loadView.setText("Loading......");
			loadView.setGravity(Gravity.CENTER);
			loadView.setTextSize((float) 16.0);
			loadView.setTextColor(Color.BLACK);
			loadingLayout = new LinearLayout(getContext());
			loadingLayout
					.setBackgroundResource(R.drawable.categories_cell_bg_on);
			// loadingLayout.addView(searchLayout, new
			// LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
			// LinearLayout.LayoutParams.WRAP_CONTENT));
			loadingLayout.addView(loadView, new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.WRAP_CONTENT,
					LinearLayout.LayoutParams.WRAP_CONTENT));
			loadingLayout.setGravity(Gravity.CENTER);
		}
	}

	OnScrollListener scrollListener = new OnScrollListener() {

		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			lastItem = firstVisibleItem + visibleItemCount - 1;
		}

		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO Auto-generated method stub
			if (lastItem == getCount()
					&& scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
				curPage = curPage + 1;
				if (curPage <= pageNum) {
					task = new GoodsListListAsync();
					task.execute(null);
				} else {
					curPage = curPage - 1;
				}
			}
		}

	};

	class GoodsListListAsync extends AsyncTask<Void, Integer, Void> {
		public GoodsListListAsync() {

		}

		@Override
		protected void onPreExecute() {
			loadingLayout.setVisibility(View.VISIBLE);
			goodsInfoList.clear();
		}

		@Override
		protected Void doInBackground(Void... params) {
			switch (action) {
			case ACTION_UNDERLIST:
				goodsInfoList = WebServiceClient.getUnder3Goods(curPage,
						shortBy, desc);
				break;
			case ACTION_HOTGOODSLIST:
				goodsInfoList = WebServiceClient.getHotGoodsList(curPage,
						shortBy, desc);
				break;
			case ACTION_NEWGOODSLIST:
				goodsInfoList = WebServiceClient.getNewGoodsList(curPage,
						shortBy, desc);
				break;
			case ACTION_SEARCHGOODSLIST:
				goodsInfoList = WebServiceClient.getGoodsListByQuery(condition,
						curPage, shortBy, desc);
				break;
			case ACTION_GOODSLISTBYCARTID:
				goodsInfoList = WebServiceClient.getGoodsListByCat(
						(short) catId, curPage, shortBy, desc);
				break;
			default:
				goodsInfoList.clear();
				break;
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			addItems(goodsInfoList);
			loadingLayout.setVisibility(View.GONE);
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
	}

	public void stop() {
		if (task != null) {
			task.cancel(true);
		}
		goodsInfoList.clear();
		if (loadingLayout != null) {
			loadingLayout.setVisibility(View.GONE);
		}
	}

	/**
	 * @param items
	 */
	public void addItems(List<GoodsInfo> items) {
		for (GoodsInfo GoodsInfo : items) {
			this.add(GoodsInfo);
		}
		this.notifyDataSetChanged();
	}

}
